﻿using GalaSoft.MvvmLight.Messaging;
using Reactive.Bindings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using WPF_ReactiveProperty_PathSearchUtil.Data_Access;
using WPF_ReactiveProperty_PathSearchUtil.Models;
using WPF_ReactiveProperty_PathSearchUtil.Service;
using WPF_ReactiveProperty_PathSearchUtil.Service.impl;
using WPF_ReactiveProperty_PathSearchUtil.Util;
using WPF_ReactiveProperty_PathSearchUtil.ViewModels.common;
using WPF_ReactiveProperty_PathSearchUtil.Views;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MessageBox = System.Windows.MessageBox;

namespace WPF_ReactiveProperty_PathSearchUtil.ViewModels
{
    public class MainWindowViewModel
    {
        #region props
        private MainWindowService mainService;
        private CSVReadOrWrite access;
        public ReactiveCollection<int> FindResult { get; }
        private int[] isDESC = { 0, 0, 0, 0, 0 };
        private int indexNow;
        private string findWord;
        public ReactiveCollection<FileInfoModel> FileList { get; }
        public ReactivePropertySlim<string> SearchPath { get; }
        public ReactivePropertySlim<bool> IsChecked { get; }
        public ReactivePropertySlim<int> SelectedIndex { get; }

        public WeakReference<Window> CurrentWindow { get; set; } = new WeakReference<Window>(null);
        #endregion

        #region command
        public ReactiveCommand WithdrawButton { get;}
        public ReactiveCommand SelectPathButton { get;}
        public ReactiveCommand DoneButton { get;}
        public ReactiveCommand FindButton { get;}
        public ReactiveCommand NextButton { get;}
        public ReactiveCommand ExCSVButton { get;}
        public ReactiveCommand ImCSVButton { get;}
        public ReactiveCommand<DataGridSortingEventArgs> SortingEvent { get; set; }
        public ReactiveCommand<KeyEventArgs> KeyDownEvent { get; set; }
        public ReactiveCommand SelectChangedEvent { get; set; }
        #endregion

        #region init
        public MainWindowViewModel(Window window)
        {
            CurrentWindow.SetTarget(window);
            mainService = new MainWindowServiceImpl();
            access = new ServerSQLite();
            //access = new LocalSQLite();
            FileList = new ReactiveCollection<FileInfoModel>();
            FindResult = new ReactiveCollection<int>();

            #region init command and props
            SearchPath = new ReactivePropertySlim<string>();
            //SearchPath.Value = "D:";
            IsChecked = new ReactivePropertySlim<bool>();
            SelectedIndex = new ReactivePropertySlim<int>();
            WithdrawButton = new ReactiveCommand();
            SelectPathButton = new ReactiveCommand();
            DoneButton = new ReactiveCommand();
            FindButton = new ReactiveCommand();
            NextButton = new ReactiveCommand();
            ExCSVButton = new ReactiveCommand();
            ImCSVButton = new ReactiveCommand();
            DoneButton = new ReactiveCommand();
            SelectChangedEvent = new ReactiveCommand();
            SortingEvent = new ReactiveCommand<DataGridSortingEventArgs>();
            KeyDownEvent = new ReactiveCommand<KeyEventArgs>();
            #endregion

            #region subscribe
            WithdrawButton.Subscribe(x => Withdraw());
            SelectPathButton.Subscribe(x => { SelectPath(); });
            FindButton.Subscribe(x => { OpenFindForm(); });
            NextButton.Subscribe(x => { SearchNext(); });
            ExCSVButton.Subscribe(x => { ExCSV(); });
            ImCSVButton.Subscribe(x => { ImCSV(); });
            SortingEvent.Subscribe(Sorting);
            KeyDownEvent.Subscribe(KeyDown);
            SelectChangedEvent.Subscribe(x => { SelectChanged(); });
            #endregion
        }
        #endregion

        #region method
        /// <summary>
        /// 抽出
        /// </summary>
        public void Withdraw()
        {
            FindResult.Clear();
            Resp resp = mainService.WithdrawPath(FileList, SearchPath.Value, IsChecked.Value);
            if (resp.Code == 0)
            {
                MessageBox.Show("抽出成功", "提示");
            }
            else
            {
                MessageBox.Show(resp.Message, "提示");
            }
        }

        /// <summary>
        /// 选择路径
        /// </summary>
        public void SelectPath()
        {
            SetSelectedIndex(33);
            FolderBrowserDialog folderDlg = new FolderBrowserDialog();
            if (folderDlg.ShowDialog() == DialogResult.OK)
            {
                SearchPath.Value = folderDlg.SelectedPath;
            }
        }

        /// <summary>
        /// 打开检索窗口
        /// </summary>
        public void OpenFindForm()
        {
            if (FileList.Count <= 0)
            {
                MessageBox.Show("没有可检索的列表。", "提示");
                return;
            }
            //注册消息接收者，回调Find
            Messenger.Default.Register<MyMessage>(this, Find);
            FindForm findForm = new FindForm();
            if (CurrentWindow.TryGetTarget(out Window win))
            {
                findForm.Owner = win;
                findForm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                findForm.ShowDialog();
            }
        }

        /// <summary>
        /// 获取消息 检索
        /// </summary>
        /// <param name="message"></param>
        public void Find(MyMessage message)
        {
            findWord = message.Messages;
            Resp resp = mainService.Find(FindResult, FileList, findWord);
            UnregisterMessage();
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message, "提示");
            }
            else
            {
                indexNow = FindResult[0];
                SetSelectedIndex(FindResult[0]);
            }
        }

        /// <summary>
        /// 清除datagrid选中效果，并选中指定行
        /// </summary>
        /// <param name="index"></param>
        public void SetSelectedIndex(int index)
        {
            SelectedIndex.Value = -1;
            SelectedIndex.Value = index;
        }

        /// <summary>
        /// 注销消息接收者
        /// </summary>
        public void UnregisterMessage()
        {
            // 取消注册接收者
            Messenger.Default.Unregister<MyMessage>(this);
        }

        /// <summary>
        /// 检索下一个
        /// </summary>
        public void SearchNext()
        {
            Resp resp = mainService.SearchNext(FindResult, FileList, findWord, indexNow);
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message, "提示");
            }
            else
            {
                indexNow = Convert.ToInt32(resp.Date);
                SetSelectedIndex(indexNow);
            }
        }

        /// <summary>
        /// 导出CSV
        /// </summary>
        public void ExCSV()
        {
            Resp resp = mainService.WriteByServerOrLocal(access, FileList);
            if (resp.Code == -2)
            {
                return;
            }
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message);
            }
            if (resp.Code == 0)
            {
                MessageBox.Show(resp.Date.ToString(), "提示");
            }
        }

        /// <summary>
        /// 读取CSV
        /// </summary>
        public void ImCSV()
        {
            Resp resp = mainService.ReadByServerOrLocal(access, FileList);
            if (resp.Code == -2)
            {
                return;
            }
            if (resp.Code != 0)
            {
                MessageBox.Show(resp.Message);
            }
            if (resp.Code == 0)
            {
                MessageBox.Show("读取成功。", "提示");
            }
        }

        /// <summary>
        /// 点击标题排序
        /// </summary>
        public void Sorting(DataGridSortingEventArgs e)
        {
            mainService.ToSort(FileList, ref isDESC, e);
        }

        /// <summary>
        /// keyDown
        /// </summary>
        /// <param name="e"></param>
        public void KeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Escape) Close();
            if (e.Key == Key.F1) ImCSV();
            if (e.Key == Key.F3) SearchNext();
            if (e.Key == Key.F7) OpenFindForm();
            if (e.Key == Key.F8) Withdraw();
            if (e.SystemKey == Key.F10) ExCSV();
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        public void Close()
        {
            UnregisterMessage();

            if (CurrentWindow.TryGetTarget(out Window win))
            {
                win.Close();
            }
        }

        /// <summary>
        /// 选中行变化，发送给view，保持选中行在画面内
        /// </summary>
        public void SelectChanged()
        {
            if (SelectedIndex.Value >= 0 && SelectedIndex.Value < FileList.Count)
            {
                var message = new MyMessage
                {
                    SelectedIndex = SelectedIndex.Value
                };
                Messenger.Default.Send(message);
            }
        }
        #endregion
    }
}
